package com.kzj.mls.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kzj.mls.R;
import com.kzj.mls.beans.ServiceBookBean;
import com.kzj.mls.global.App;
import com.kzj.mls.global.Constant;
import com.kzj.mls.recyclerCard.basic.MaterialListView;
import com.kzj.mls.recyclerCard.basic.OnButtonPressListener;
import com.kzj.mls.recyclerCard.card.Card;
import com.kzj.mls.recyclerCard.card.other.AddressManagerCard;
import com.kzj.mls.request.BaseResponse;
import com.kzj.mls.request.ICallBackForRequestServer;
import com.kzj.mls.request.RequestServerManager;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by xyg on 2015/11/3.
 */
public class AddressManagerActivity extends GBaseActivity {
    private MaterialListView material_listview;
    private List<ServiceBookBean.HomeAddressEntity> addressBeans;
    private TextView textView_add;
    private ServiceBookBean serviceBookBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentViewFor720_1280(R.layout.activity_address_manager);
        findViewByIds();
        initDatas();
        if (serviceBookBean == null)
            TaskGetAddressList(App.getInstance().getUserBean().getUser_checked());
    }

    @Override
    protected void findViewByIds() {
        material_listview = (MaterialListView) findViewById(R.id.material_listview);
        textView_add = (TextView) findViewById(R.id.textView_add);
        textView_add.setOnClickListener(this);
    }

    @Override
    protected void initDatas() {
        setTopTitle("服务地址管理 ");
        setRightText(View.VISIBLE, "完成");
        setLeftImg(View.VISIBLE, R.drawable.back);
        EventBus.getDefault().register(this);
        serviceBookBean = (ServiceBookBean) getIntent().getSerializableExtra("beans");
        if (serviceBookBean != null) {
            addressBeans = serviceBookBean.getAddr();
            fillArrayInListView();
        }
    }

    public void onEventMainThread(List<ServiceBookBean.HomeAddressEntity> homeAddressEntity) {
        addressBeans = homeAddressEntity;
        fillArrayInListView();
    }

    public void onEventMainThread(ServiceBookBean serviceBookBean) {
        this.serviceBookBean = serviceBookBean;
        addressBeans = serviceBookBean.getAddr();
        fillArrayInListView();
    }

    @Override
    protected void fillArrayInListView() {
        material_listview.clear();
        for (int i = 0; i < addressBeans.size(); i++) {
            AddressManagerCard addressManagerCard = new AddressManagerCard(this);
            addressManagerCard.setAddressBean(addressBeans.get(i));
            final int finalI = i;
            addressManagerCard.setOnNormalButtonPressedListener(new OnButtonPressListener() {
                @Override
                public void onButtonPressedListener(View view, Card card) {
                    if (view.getId() == R.id.imageView_delete) {
                        TaskDeleteAddress(((AddressManagerCard) card).getAddressBean().getAddr_id(), ((AddressManagerCard) card).getAddressBean());
                    } else {
                        Intent intent = new Intent(AddressManagerActivity.this, EditAddressActivity.class);
                        intent.putExtra("address_bean", ((AddressManagerCard) card).getAddressBean());
                        intent.putExtra("beans", serviceBookBean);
                        startActivity(intent);
                    }
                }
            });
            material_listview.add(addressManagerCard);
        }
    }


    private void TaskGetAddressList(String user_checked) {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Address_List, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Address_List, user_checked), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        addressBeans = JSON.parseArray(result.getRetval().toString(), ServiceBookBean.HomeAddressEntity.class);
                        fillArrayInListView();
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    private void TaskDeleteAddress(final String addr_id, final ServiceBookBean.HomeAddressEntity homeAddressEntity) {
        RequestServerManager.getInstance().handleMethod((GBaseActivity) getActivity(), null, null, false,
                Constant.getRootUrl() + Constant.Action.Action_Delete_Address, RequestServerManager.getInstance().
                        getRequestParams(Constant.Action.Action_Delete_Address, addr_id), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        if (serviceBookBean != null) {
                            addressBeans = JSON.parseArray(result.getRetval().toString(), ServiceBookBean.HomeAddressEntity.class);
                            serviceBookBean.setAddr(addressBeans);
                            fillArrayInListView();
                            EventBus.getDefault().post(serviceBookBean);
                        } else {
                            addressBeans = JSON.parseArray(result.getRetval().toString(), ServiceBookBean.HomeAddressEntity.class);
                            fillArrayInListView();
                        }
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        App.getInstance().showToast(errorMsg + "");
                    }
                });
    }

    @Override
    public void doClickRightText() {
        super.doClickRightText();
        this.finish();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.textView_add:
                Intent intent = new Intent(this, EditAddressActivity.class);
                intent.putExtra("beans", serviceBookBean);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName()); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写)
        MobclickAgent.onResume(this);          //统计时长
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName()); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息
        MobclickAgent.onPause(this);
    }
}
